package com.ikingtech.framework.sdk.extension.collector;

import com.ikingtech.framework.sdk.context.exception.FrameworkException;
import com.ikingtech.framework.sdk.core.response.R;
import com.ikingtech.framework.sdk.extension.collector.model.ExtensionInfoCollectParam;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author tie yan
 */
@Slf4j
@RequiredArgsConstructor
public class ExtensionInfoCollectResolver {

    private final List<ExtensionInfoCollector> collectors;

    @PostMapping("/extension/info/collect/resolve")
    public R<Object> resolve(@RequestBody ExtensionInfoCollectParam param) {
        if (null == param) {
            throw new FrameworkException("EXTENSION INFO COLLECT RESOLVER", "extensionInfoCollectParamIsBlank");
        }
        switch (param.type()) {
            case QUERY_FOR_IDS -> {
                List<String> ids = new ArrayList<>();
                this.collectors.forEach(collector -> ids.addAll(collector.queryForIds(param.queryParam())));
                return R.ok(ids);
            }
            case QUERY_BY_IDS -> {
                Map<String, Map<String, Object>> extensionInfos = new HashMap<>();
                this.collectors.forEach(collector -> {
                    Map<String, Map<String, Object>> extensionInfoMap = collector.queryByIds(param.ids().getList());
                    extensionInfoMap.forEach((userId, extensionInfo) -> {
                        if (extensionInfos.containsKey(userId)) {
                            extensionInfos.get(userId).putAll(extensionInfo);
                        } else {
                            extensionInfos.put(userId, extensionInfo);
                        }
                    });
                });
                return R.ok(extensionInfos);
            }
            case QUERY_BY_ID -> {
                Map<String, Object> extensionInfo = new HashMap<>();
                this.collectors.forEach(collector -> extensionInfo.putAll(collector.queryById(param.id())));
                return R.ok(extensionInfo);
            }
        }
        throw new FrameworkException("invalidExtensionInfoCollectType");
    }
}
